import Redis from 'ioredis';
import { redisConfig, redisClusterConfig } from '../config/redis.config';

export class RedisInstance {
  static initRedis(db?: number, connectType?: string) {
    if (connectType && connectType === 'cluster') {
      const cluster = new Redis.Cluster(redisClusterConfig);
      cluster.on('error', (err) => console.log('Redis cluster Error', err));
      cluster.on('connect', () => console.log('redis集群连接成功'));
      return cluster;
    } else {
      let newDB = 0
      if(db !== undefined){
        newDB = db
      }else if(process.env.redisdb === undefined || process.env.redisdb === '' || process.env.redisdb === '1'){
        newDB = 1
      }
      redisConfig.db = newDB
      const redis = new Redis(redisConfig);
      redis.on('error', (err) => console.log('Redis cluster Error', err));
      redis.on('connect', () => console.log('redis连接成功'));
      return redis;
    }
  }
}
